import json

import requests

app_id = "6c31123d-6103-4e6d-a546-f8fce6555807"
auth = 'Bearer bce-v3/ALTAK-WT80OnqVYqiuiXVWpaWYc/448dafad3a1809cdd625d6aeb7b337e73556999d'

# 步骤1：新建会话，得到conversation_id
url = "https://qianfan.baidubce.com/v2/app/conversation"

payload = json.dumps({
    "app_id": app_id
})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': auth
}

response = requests.request("POST", url, headers=headers, data=payload)

# 从以上json字符串中提取conversation_id
data = json.loads(response.text)
conversation_id = data['conversation_id']

# 步骤1,2之间加出来的，上传图片获取file_id
url = "https://qianfan.baidubce.com/v2/app/conversation/file/upload"

payload = {
    'app_id': app_id,
    'conversation_id': conversation_id
}
# todo 图片改成前端上传
files = [
    ('file', ('1.jpg', open('img/1.jpg', 'rb'), 'image/jpeg'))
]
headers = {
    'X-Appbuilder-Authorization': auth
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

# print(response.text)

file_id = json.loads(response.text)['id']


# 步骤2：发送请求，得到AppBuilder的结果
url = "https://qianfan.baidubce.com/v2/app/conversation/runs"

payload = json.dumps({
    "app_id": app_id,
    "query": input('请输入问题:'),
    "stream": False,
    "conversation_id": conversation_id,
    "file_ids": [
        file_id
    ]
})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': auth
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

# 从以上json字符串中提取conversation_id
data = json.loads(response.text)
answer = data['answer']
